<template>
  <div class="right">
    <div class="nav-title"><span></span>
      <p>角色权限</p>
    </div>
    <div class="dataList">
      <div class="from">
        <el-form
          :inline="true"
          class="demo-form-inline"
        >
          <el-form-item>
            <el-button
              type="primary"
              style="float:right;"
              @click="addHandler()"
            >新增</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div>
        <el-table
          :data="tableData"
          v-loading="loading1"
          border
          style="width: 100%"
        >
          <el-table-column
            type="index"
            label="序号"
            width="180"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="NAME"
            label="角色名称"
            align="center"
            width="180"
          >
          </el-table-column>
          <el-table-column
            prop="NT"
            align="center"
            label="角色描述"
          >
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="350"
          >
            <template slot-scope="scope">
              <el-button
                @click="grantHandler(scope.row)"
                type="warning"
                size="small"
                plain
              >角色授权</el-button>
              <el-button
                @click="uersHandler(scope.row)"
                type="warning"
                size="small"
                plain
              >关联用户</el-button>
              <el-button
                @click="editHandler(scope.row)"
                type="primary"
                size="small"
                plain
              >编辑</el-button>
              <el-button
                @click='deleteHandler(scope.row)'
                type="danger"
                size="small"
                plain
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!-- 关联用户 -->
    <div class="glusers">
      <el-dialog
        title="关联用户"
        width='63%'
        :visible.sync="dialogUserVisible"
      >
        <el-form
          :inline="true"
          :model="gusers"
          ref="roleform4Users"
          :rules='rules'
        >
          <el-form-item
            label="角色名称"
            :label-width="formLabelWidth"
          >
            <el-input
              :disabled="true"
              v-model="gusers.roleName"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="用户名称"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="gusers.realName"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="所在地区"
            :label-width="formLabelWidth"
          >
            <el-cascader
              :options="addUsersOpt"
              v-model="addUsersAdcd"
              :props="adcdProps"
              change-on-select
            ></el-cascader>
          </el-form-item>
          <el-form-item>
            <el-button
              plain
              type="primary"
              size="small"
              @click="queryUsersHandler"
            >查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button
              plain
              type="primary"
              size="small"
              @click="addUsersHandler"
            >新增</el-button>
          </el-form-item>
        </el-form>
        <div class="innerTbl">

          <el-table
            border
            ref="multipleTable"
            :data="tableData3"
            tooltip-effect="dark"
            style="width: 100%"
            @selection-change="handleSelectionChange"
            v-loading='loading2'
          >
            <el-table-column
              type="selection"
              width="55"
              align="center"
            >
            </el-table-column>
            <el-table-column
              label="用户名称"
              align="center"
              prop="REALNAME"
            >
            </el-table-column>
            <el-table-column
              prop="UNAME"
              align="center"
              label="用户账号"
            >
            </el-table-column>
            <el-table-column
              align="center"
              prop="AD_NM"
              label="所在地区"
              show-overflow-tooltip
            >
            </el-table-column>
          </el-table>
        </div>
        <div class="pagenation">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </div>
        <div
          slot="footer"
          class="dialog-footer"
        >
          <el-button @click="dialogUserVisible = false">取 消</el-button>
          <el-button
            type="danger"
            @click="delRole4Users"
          >删 除</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 内层对话框 -->
    <el-dialog
      width="63%"
      title="分配用户"
      :visible.sync="innerVisible"
      append-to-body
    >
      <el-form
        :inline="true"
        :model="ausers"
        ref="roleform4AUsers"
        :rules='rules'
      >
        <el-form-item
          label="用户名称"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="ausers.realName"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="所在地区"
          :label-width="formLabelWidth"
        >
          <el-cascader
            :options="addUsersOpt4"
            v-model="addUsersAdcd4"
            :props="adcdProps"
            change-on-select
          ></el-cascader>
        </el-form-item>
        <el-form-item>
          <el-button
            plain
            type="primary"
            size="small"
            @click="queryAllUsersHandler"
          >查询</el-button>
        </el-form-item>
      </el-form>
      <div>
        <el-table
          v-loading="loading3"
          border
          ref="multipleTable4"
          :data="tableData4"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange4"
        >
          <el-table-column
            type="selection"
            width="55"
            align="center"
          >
          </el-table-column>
          <el-table-column
            label="用户名称"
            align="center"
            prop="REALNAME"
          >
          </el-table-column>
          <el-table-column
            prop="UNAME"
            align="center"
            label="用户账号"
          >
          </el-table-column>
          <el-table-column
            align="center"
            prop="ADNM"
            label="所在地区"
            show-overflow-tooltip
          >
          </el-table-column>
        </el-table>
      </div>
      <div class="pagenation">
        <el-pagination
          @size-change="handleSizeChange4"
          @current-change="handleCurrentChange4"
          :current-page="currentPage4"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pagesize4"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total4"
        >
        </el-pagination>
      </div>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="innerVisible = false">取 消</el-button>
        <el-button
          type="danger"
          @click="submitUsers4Role"
        >确 定</el-button>
      </div>
    </el-dialog>
    <!-- 新增角色 -->
    <div>
      <el-dialog
        title="新增角色"
        :visible.sync="dialogAddVisible"
      >
        <el-form
          :model="arole"
          ref="roleform4Add"
          :rules='rules'
        >
          <el-form-item
            label="角色名称"
            :label-width="formLabelWidth"
            prop="roleName"
          >
            <el-input
              v-model="arole.roleName"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="角色描述"
            :label-width="formLabelWidth"
          >
            <el-input
              type="textarea"
              v-model="arole.nt"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-form>
        <div
          slot="footer"
          class="dialog-footer"
        >
          <el-button @click="dialogAddVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="submitRole4Users"
          >确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 修改角色 -->
    <div>
      <el-dialog
        title="编辑角色"
        :visible.sync="dialogEditVisible"
      >
        <el-form
          :model="erole"
          ref="roleform4Edit"
          :rules='rules'
        >
          <el-form-item
            label="角色名称"
            :label-width="formLabelWidth"
            prop="roleName"
          >
            <el-input
              v-model="erole.roleName"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="角色描述"
            :label-width="formLabelWidth"
          >
            <el-input
              type="textarea"
              v-model="erole.nt"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-form>
        <div
          slot="footer"
          class="dialog-footer"
        >
          <el-button @click="dialogEditVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="submitRole4Edit"
          >确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 角色授权弹窗 -->
    <div class="grant">
      <el-dialog
        title="角色授权"
        :visible.sync="dialogVisible4Grant"
        width="50%"
      >
        <el-tree
          ref='tree'
          node-key="id"
          :default-checked-keys='selectTree'
          default-expand-all
          :props="treeProps"
          :data="treeData"
          show-checkbox
        >
        </el-tree>

        <span
          slot="footer"
          class="dialog-footer"
        >
          <el-button @click="dialogVisible4Grant = false">取 消</el-button>
          <el-button
            type="primary"
            @click="submitGrant"
          >确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import {
  userList,
  getModules,
  postRolesList,
  grantRoles,
  putRoleModules,
  saveRole,
  editRole,
  adcdList,
  saveRoleUsers,
  delRoleUsers,
  getUserByRoleid,
  getMoudlesByRoleId
} from "@/components/api/api.js";
export default {
  data() {
    return {
      loading1: true,
      loading2: true,
      loading3: true,
      currentPage: 1,
      pagesize: 10,
      total: 100,
      currentPage4: 1,
      pagesize4: 10,
      total4: 100,
      tableData3: [],
      tableData4: [],
      multipleSelection: [],
      multipleSelection4: [],
      adcdProps: {
        value: "id",
        label: "text"
      },
      addUsersOpt: [],
      addUsersOpt4: [],
      addUsersAdcd: [],
      addUsersAdcd4: [],
      roleid: "",
      selectTree: [],
      treeData: [],
      treeProps: {
        // 作用：匹配树的节点名称和子节点数据名称
        label: "text",
        children: "children"
      },
      ausers: {
        realName: "",
        roleName: "",
        roleId: ""
      },
      gusers: {
        realName: "",
        roleName: "",
        roleId: ""
      },
      arole: {
        roleName: "",
        nt: ""
      },
      erole: {
        roleName: "",
        nt: "",
        roleid: ""
      },
      rules: {
        roleName: [{ required: true, message: "请输入角色名", trigger: "blur" }]
      },
      dialogAddVisible: false,
      dialogEditVisible: false,
      dialogVisible4Grant: false,
      dialogUserVisible: false,
      innerVisible: false,
      formLabelWidth: "120px",
      tableData: []
    };
  },
  methods: {
    delRole4Users() {
      let userids = this.multipleSelection.map((item, index) => {
        return item.USERID;
      });
      let params = {
        userId: userids,
        roleId: this.gusers.roleId
      };
      delRoleUsers(params).then(res => {
        if (res.result === 1) {
          // 刷新列表
          this.queryUsersHandler();
          // 提示
          this.$message({
            message: "删除成功",
            type: "success"
          });
        }
      });
    },
    submitUsers4Role() {
      debugger
      let userids = this.multipleSelection4.map((item, index) => {
        return item.USERID;
      });
      let params = {
        userId: userids,
        roleId: this.gusers.roleId
      };
      saveRoleUsers(params).then(res => {
        if (res.result === 1) {
          // 刷新列表
          this.innerInit();
          this.innerVisible = false;
          // 提示
          this.$message({
            message: "新增成功",
            type: "success"
          });
        }
      });
    },
    // 查询用户
    queryAllUsersHandler() {
      let params = {
        filter: this.gusers.roleId,
        adcd: this.addUsersAdcd4[this.addUsersAdcd4.length - 1],
        realname: this.ausers.realName
      };
      this.currentPage4 = 1;
      userList(params, {
        headers: {
          Rang: "max=" + this.currentPage4 + ";size=" + this.pagesize4 + ";",
          "Content-Type": "application/json"
        }
      }).then(res => {
        if (res.result && res.paging) {
          this.tableData4 = Object.values(res.result);
          this.total4 = res.paging.total;
        } else {
          this.tableData4 = [];
          this.total4 = 0;
        }
        this.loading3 = false;
      });
    },
    // 分页-当前页
    // 选择一页条数
    handleSizeChange(val) {
      this.pagesize = val;
      // this.getUserByRoleid();
      this.queryUsersHandler();
    },
    // 选择当前页
    handleCurrentChange(val) {
      this.currentPage = val;
      // this.getUserByRoleid();
      this.queryUsersHandler();
    },
    handleSizeChange4(val) {
      this.pagesize4 = val;
      this.innerInit();
    },
    // 选择当前页
    handleCurrentChange4(val) {
      let $this = this;
      $this.currentPage4 = val;
      $this.innerInit();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleSelectionChange4(val) {
      this.multipleSelection4 = val;
    },
    // 角色关联用户查询
    queryUsersHandler() {
      let checkedAdcd = this.addUsersAdcd[this.addUsersAdcd.length - 1];
      let params = {
        roleid: this.gusers.roleId,
        adcd: checkedAdcd,
        realname: this.gusers.realName
      };
      getUserByRoleid(params, {
        headers: {
          Rang: "max=" + this.currentPage + ";size=" + this.pagesize + ";",
          "Content-Type": "application/json"
        }
      }).then(res => {
        if (res.result) {
          this.tableData3 = Object.values(res.result);
          this.total = 10;
        } else {
          this.tableData3 = [];
          this.total = 0;
        }
        this.loading2 = false;
      });
    },
    uersHandler(row) {
      adcdList().then(res => {
        this.addUsersOpt.push(res.result);
      });
      this.gusers.roleName = row.NAME;
      this.gusers.roleId = row.ROLEID;
      this.gusers.realName = "";
      this.queryUsersHandler();
      this.dialogUserVisible = true;
    },
    innerInit() {
      userList(
        { filter: this.gusers.roleId },
        {
          headers: {
            Rang: "max=" + this.currentPage4 + ";size=" + this.pagesize4 + ";",
            "Content-Type": "application/json"
          }
        }
      ).then(res => {
        if (res.result && res.paging) {
          this.tableData4 = Object.values(res.result);
          this.total4 = res.paging.total;
        } else {
          this.tableData4 = [];
          this.total4 = 0;
        }
        // this.loading3 = true;
      });
      this.loading3 = false;
    },
    submitRole4Users() {
       this.$refs["roleform4Add"].validate(valid => {
        if (valid) {
          // 提交表单
          saveRole(this.arole).then(res => {
            if (res.result === 1) {
              // 关闭窗口
              this.dialogAddVisible = false;
              // 刷新列表
              this.initList();
            }
          });
        }
      });
    },
    addUsersHandler() {
      // 角色分配新增用户
      this.ausers.realName = "";
      this.addUsersAdcd4 = [];
      this.innerInit();

      adcdList().then(res => {
        this.addUsersOpt4 = [{ text: "全部", id: null, pid: null }];
        this.addUsersOpt4.push(res.result);
      });

      this.innerVisible = true;
    },
    grantHandler(row) {
      this.roleid = row.ROLEID;
      this.selectTree = [];
      // this.treeData = []
      // 初始化数据
      getMoudlesByRoleId(row)
        .then(res => {
          if (!res.result) return false;

          res.result.forEach(item => {
            this.selectTree.push(item.MODULE_ID);
          });
        })
        .then(res => {
          getModules().then(res => {
            // 初始化树结构的数据
            this.treeData=[res.result];
          });
          // 显示弹窗
          this.dialogVisible4Grant = true;
        });
    },
    submitGrant() {
      // 获取所有选中节点的数据对象列表
      let list = this.$refs["tree"].getCheckedNodes();
      let ids = list.map(item => {
        return item.id;
      });
      // 调用后台接口提交数据
      putRoleModules({ roleId: this.roleid, modulesId: ids }).then(res => {
        if (res.result === 1) {
          // 刷新列表
          this.initList();
          // 关闭弹窗
          this.dialogVisible4Grant = false;
          // 提示
          this.$message({
            message: "菜单分配成功",
            type: "success"
          });
        }
      });
    },
    // 新增角色弹窗
    addHandler() {
      this.arole.roleName = "";
      this.arole.nt = "";
      this.dialogAddVisible = true;
    },
    // 新增角色确定
    submitRole4Add() {
      // 编辑提交用户
      this.$refs["roleform4Add"].validate(valid => {
        if (valid) {
          // 提交表单
          saveRole(this.arole).then(res => {
            if (res.result === 1) {
              // 关闭窗口
              this.dialogAddVisible = false;
              // 刷新列表
              this.initList();
            }
          });
        }
      });
    },
    // 编辑角色弹窗
    editHandler(row) {
      this.erole.roleName = row.NAME;
      this.erole.nt = row.NT;
      this.erole.roleid = row.ROLEID;
      this.dialogEditVisible = true;
    },
    // 编辑角色确定
    submitRole4Edit() {
      // 编辑提交用户
      this.$refs["roleform4Edit"].validate(valid => {
        if (valid) {
          // 提交表单
          editRole(this.erole).then(res => {
            if (res.result === 1) {
              // 关闭窗口
              this.dialogEditVisible = false;
              // 刷新列表
              this.initList();
            }
          });
        }
      });
    },
    // 删除角色确定
    deleteHandler(row) {
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          // 确定要删除，然后调用接口
          editRole({ roleid: row.ROLEID, delflag: "1" }).then(res => {
            if (res.result === 1) {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              // 刷新列表
              this.initList();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    initList() {
      postRolesList().then(res => {
        if (!res.result) return false;
        this.tableData = res.result;
        this.loading1 = false;
      });
    }
  },
  mounted() {
    this.initList();
  }
};
</script>
<style scoped>
.glusers .el-form-item:last-child {
  float: right;
}
.right {
  border: 1px solid #e7e7e7;
  box-shadow: 0 0 4px #e7e7e7;
  background: #fff;
  border-radius: 5px;
}
.nav-title {
  height: 50px;
  display: -ms-flexbox;
  display: flex;
  width: 98%;
  margin: 0 auto;
  -ms-flex-align: center;
  align-items: center;
  border-bottom: 1px solid #f0f0f0;
}
.nav-title span {
  display: inline-block;
  width: 0px;
  height: 18px;
  border-radius: 5px;
  border-left: 4px solid #3380f3;
}
.nav-title p {
  padding-left: 10px;
  font-weight: 600;
}
.dataList {
  padding: 10px;
  /* height: 610px; */
}
.from {
  height: 50px;
}
.from .el-form-item:last-child {
  position: absolute;
  right: 30px;
}
.el-table {
  height: 400px;
  overflow: auto;
}
.el-dialog .el-table {
  height:300px;
}
.pagenation {
  text-align: center;
  margin-top: 0.1rem;
}
.el-cascader {
  width: 100%;
}
.grant {
  height: 30%;
}
.el-tree {
  overflow-y: auto;
  height: 400px;
}
</style>
